package com.mini.admin.config;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * 项目启动后获取所有的url
 * @author Zhou Feng
 */
@Component
public class AggregationPermissions implements CommandLineRunner {

    @Autowired
    private WebApplicationContext applicationContext;

    @Override
    public void run(String... args) throws Exception {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
        Set<Map.Entry<RequestMappingInfo, HandlerMethod>> entrySet = handlerMethods.entrySet();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : entrySet) {
            RequestMappingInfo requestMappingInfo = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();
            Method method = handlerMethod.getMethod();
            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
            Api api = method.getDeclaringClass().getAnnotation(Api.class);
            if (api==null||apiOperation==null){
                continue;
            }
            String[] apiGroups = api.tags();
            String apiName = apiOperation.value();
            Set<String> apiSet = requestMappingInfo.getPatternsCondition().getPatterns();
            System.out.println(Arrays.toString(apiGroups) +"{"+apiName+"="+apiSet+"}");
        }
    }
}
